<?php

namespace app\common\model;
use app\common\model\Goods as GoodsModel;
use think\Cache;
use app\common\model\UploadFile as UploadFileModel;
use think\db;
/**
 * 拼团商品分类模型
 * Class Category
 * @package app\common\model
 */
class Category extends BaseModel
{
    protected $name = 'category';

    /**
     * 分类图片
     * @return \think\model\relation\HasOne
     */
    public function image()
    {
        return $this->hasOne('uploadFile', 'file_id', 'image_id');
    }

    /**
     * 所有分类
     * @return mixed
     */
    public static function getALL($is_show = false)
    {
        $where = [];
//        $where['parent_id'] = ['neq',0];
        if ($is_show) $where['is_show'] = 1;
        $flag = (int)$is_show;
        $model = new static;
        //if (!Cache::get('category_' . $model::$wxapp_id . '_' . $flag)) {
        $data = $model->with(['image'])->where($where)->order(['sort' => 'asc', 'create_time' => 'asc'])->select();
        $all = !empty($data) ? $data->toArray() : [];
        $tree = [];
        foreach ($all as $first) {
            if ($first['parent_id'] != 0) continue;
            $twoTree = [];
            $goodsmodel = new GoodsModel();


            $childcates = self::getUnderlingUIds($first['category_id']);

            $where1 = "category_id in ($childcates)";
            $where1 .= " AND  is_delete = 0 AND goods_status = 10";
            $categoods = $goodsmodel->with(['image'])->where($where1)->order('goods_sort','asc')->select();

            // $cateimage = Db::name('upload_file')->where(array("file_id"=>$first['image_id']))->find();

            $uploadFile = new UploadFileModel;

            $cateimage = $uploadFile->detail($first['image_id']);

            // $first['cateimage'] = $_SERVER['SERVER_NAME']."/uploads/".$cateimage['file_name'];
            $first['cateimage'] = $cateimage['file_path'];

            $childcate = Db::name('category')->where(array("parent_id"=>$first['category_id']))->select();
            $first['childcate'] = $childcate;



            foreach($categoods as $key=>$val){
                // $image_file = Db::name('upload_file')->where(array("file_id"=>$val['image'][0]['image_id']))->find();
                $image_file = $uploadFile->detail($val['image'][0]['image_id']);

                if($image_file['file_path'] !=""){
                    // $categoods[$key]['image_file'] =  $_SERVER['SERVER_NAME']."/uploads/".$image_file['file_name'];
                    $categoods[$key]['image_file'] =  $image_file['file_path'];

                }else{
                    $categoods[$key]['image_file'] =  $_SERVER['SERVER_NAME']."/success.png";
                }

                $goodssku = Db::name('goods_sku')->where(array("goods_id"=>$val['goods_id']))->find();
                $categoods[$key]['goods_price'] =$goodssku['goods_price'];
            }

            foreach ($all as $two) {
                if ($two['parent_id'] != $first['category_id']) continue;
                $threeTree = [];
                foreach ($all as $three)
                    $three['parent_id'] == $two['category_id']
                    && $threeTree[$three['category_id']] = $three;
                !empty($threeTree) && $two['child'] = $threeTree;
                $twoTree[$two['category_id']] = $two;
            }
            if (!empty($twoTree)) {
                array_multisort(array_column($twoTree, 'sort'), SORT_ASC, $twoTree);
                $first['child'] = $twoTree;
            }
            $first['goods'] = $categoods;
            $tree[$first['category_id']] = $first;


        }
        Cache::tag('cache')->set('category_' . $model::$wxapp_id . '_' . $flag, compact('all', 'tree'));
        //}
        return Cache::get('category_' . $model::$wxapp_id . '_' . $flag);
    }

    public static function getUnderlingUIds($uid, $ids='')
    {
        $back = Db::name('category')->where(array('parent_id'=>$uid))->select()->toArray();
        if (!empty($back) && is_array($back)) {
            foreach ($back as $v) {
                //防止当前人的ID重复去查询，形成恶性循环
                if ($v['category_id'] == $uid) {
                    continue;
                }
                $back2 = Db::name('category')->where(array('parent_id'=>$v['category_id']))->count('category_id');
                if ($back2 > 0) {
                    $ids = self::getUnderlingUIds($v['category_id'],$ids);
                } else {
                    $ids .= ','.$v['category_id'];
                }
            }
        }
        $ids = $uid.','.$ids.',';
        $ids = str_replace(',,', ",", $ids);
        $ids = trim($ids, ',');
        return $ids;
    }
    /**
     * 获取所有分类
     * @return mixed
     */
    public static function getCacheAll($is_show = false)
    {
        return self::getALL($is_show)['all'];
    }

    /**
     * 获取所有分类(树状结构)
     * @return mixed
     */
    public static function getCacheTree($is_show = false)
    {
        return self::getALL($is_show)['tree'];
    }

    /**
     * 获取所有分类(树状结构)
     * @return string
     */
    public static function getCacheTreeJson()
    {
        return json_encode(static::getCacheTree());
    }

    /**
     * 获取指定分类下的所有子分类id
     * @param $parent_id
     * @param array $all
     * @return array
     */
    public static function getSubCategoryId($parent_id, $all = [])
    {
        $arrIds = [$parent_id];
        empty($all) && $all = self::getCacheAll();
        foreach ($all as $key => $item) {
            if ($item['parent_id'] == $parent_id) {
                unset($all[$key]);
                $subIds = self::getSubCategoryId($item['category_id'], $all);
                !empty($subIds) && $arrIds = array_merge($arrIds, $subIds);
            }
        }
        return $arrIds;
    }

    /**
     * 指定的分类下是否存在子分类
     * @param $parentId
     * @return bool
     */
    protected static function hasSubCategory($parentId)
    {
        $all = self::getCacheAll();
        foreach ($all as $item) {
            if ($item['parent_id'] == $parentId) {
                return true;
            }
        }
        return false;
    }

}
